package com.oocl.ha.merchant.websocket.handler;
import java.io.IOException;  
import java.util.concurrent.CopyOnWriteArraySet;  
  
import javax.websocket.OnClose;  
import javax.websocket.OnError;  
import javax.websocket.OnMessage;  
import javax.websocket.OnOpen;  
import javax.websocket.Session;  
import javax.websocket.server.ServerEndpoint;  
  
@ServerEndpoint(value="/websocket")  
public class MyWebSocket {  
      

    private static int onlineCount = 0;  
       
 
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();  
       

    private Session session;  
    
    private static String name;
  
    @OnOpen  
    public void onOpen(Session session){  
        this.session = session;  
        webSocketSet.add(this);     
        addOnlineCount();           
        name=session.getId();
        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());  
    }  
       
    /** 
     * 连接关闭调用的方法 
     */  
    @OnClose  
    public void onClose(){  
        webSocketSet.remove(this);  
        subOnlineCount();               
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());  
    }  
       
 
    @OnMessage  
    public void onMessage(String message, Session session) {  
        System.out.println("您有新订单:" + message);  
           
   
        for(MyWebSocket item: webSocketSet){               
            try {  
//            	if (item.session.getId()==name) {
            		System.out.println("111111111111111111111");
            		item.sendMessage(message);  				
            		System.out.println("22222222222222222222222");
//				}
            } catch (IOException e) {  
                e.printStackTrace();  
                continue;  
            }  
        }  
    }  
       

    @OnError  
    public void onError(Session session, Throwable error){  
        System.out.println("发生错误");  
        error.printStackTrace();  
    }  
       

    public void sendMessage(String message) throws IOException{  
        this.session.getBasicRemote().sendText(message);  
        //this.session.getAsyncRemote().sendText(message);  
    }  
   
    public static synchronized int getOnlineCount() {  
        return onlineCount;  
    }  
   
    public static synchronized void addOnlineCount() {  
        MyWebSocket.onlineCount++;  
    }  
       
    public static synchronized void subOnlineCount() {  
        MyWebSocket.onlineCount--;  
    }  
  
}  